package com.bang.concurrency.example.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Auther: Bang
 * @Date: 2019/10/4 22:58
 * @Description:
 */
@Slf4j
public class ReentrantReadWriteLockExample {

    private static final Map<String, Data> map = new TreeMap<>();

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private static Lock readLock = lock.readLock();

    private static Lock writeLock = lock.writeLock();

    class Data {
    }

    public static void put(String key, Data value) {
        writeLock.lock();
        try {
            map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

    public static Data get(String key) {
        readLock.lock();
        try {
           return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public static Set<String> getAllKeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

}
